package com.hxci.hospital.tool;

import com.hxci.hospital.pojo.Patient;
import com.hxci.hospital.service.PatientService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.function.Function;

@Configuration
public class HospitalTools {
    @Autowired
    private PatientService patientService;

    public record MakeAppointmentRequest(
            String name, 
            String gender, 
            String age, 
            String phone, 
            String idCard, 
            String symptoms, 
            String department, 
            String appointmentDate, 
            String appointmentTime
    ) {}

    @Bean
    @Description("为患者挂号")
    public Function<MakeAppointmentRequest, String> makeAppointment() {
        return request -> {
            Patient patient = new Patient();
            patient.setName(request.name());
            patient.setGender(request.gender());
            patient.setAge(request.age());
            patient.setPhone(request.phone());
            patient.setIdCard(request.idCard());
            patient.setSymptoms(request.symptoms());
            patient.setDepartment(request.department());
            patient.setAppointmentDate(request.appointmentDate());
            patient.setAppointmentTime(request.appointmentTime());

            // 根据科室分配医生（简化处理，实际应用中可能需要更复杂的逻辑）
            String doctor = assignDoctorByDepartment(request.department());
            patient.setDoctor(doctor);

            // 设置创建时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            patient.setCreateTime(sdf.format(new Date()));

            // 初始状态为待就诊
            patient.setStatus(0);

            // 保存患者信息
            Integer result = patientService.add(patient);

            if (result > 0) {
                return String.format("挂号成功！您的就诊信息如下：\n姓名：%s\n科室：%s\n医生：%s\n就诊日期：%s\n就诊时间：%s\n请按时就诊。", 
                        request.name(), request.department(), doctor, request.appointmentDate(), request.appointmentTime());
            } else {
                return "挂号失败，请稍后再试或联系医院工作人员。";
            }
        };
    }

    // 根据科室分配医生的简化方法
    private String assignDoctorByDepartment(String department) {
        // 实际应用中应该从数据库查询对应科室的医生
        // 这里简化处理，直接返回科室名称作为医生姓名
        switch (department) {
            case "内科":
                return "张医生";
            case "外科":
                return "李医生";
            case "儿科":
                return "王医生";
            case "妇产科":
                return "刘医生";
            case "眼科":
                return "陈医生";
            case "耳鼻喉科":
                return "赵医生";
            default:
                return "值班医生";
        }
    }
}
